package org.gdstash.db;

import org.gdstash.util.GDMsgFormatter;
import org.gdstash.util.GDMsgLogger;

import java.sql.*;
import java.util.LinkedList;
import java.util.List;

public class DBEngineSkillMasterAlloc {
    public static final String TABLE_NAME = "GDC_SKILL_MASTER";
    private static final int ROW_CLASSTABLE_ID = 1;

    public static void createTable(final Connection conn) throws SQLException {
        final String dropTable = "DROP TABLE GDC_SKILL_MASTER";
        final String createTable = "CREATE TABLE GDC_SKILL_MASTER (CLASSTABLE_ID  VARCHAR(256) NOT NULL, PRIMARY KEY (CLASSTABLE_ID))";
        try (final Statement st = conn.createStatement()) {
            if (GDDBUtil.tableExists(conn, "GDC_SKILL_MASTER")) {
                st.execute(dropTable);
            }
            st.execute(createTable);
            st.close();
            conn.commit();
        } catch (SQLException ex) {
            throw ex;
        }
    }

    public static void insert(final Connection conn, final DBEngineSkillMaster dbSkillMaster) throws SQLException {
        if (dbSkillMaster.getClassTableList() == null) {
            return;
        }
        if (dbSkillMaster.getClassTableList().isEmpty()) {
            return;
        }
        final String insert = "INSERT INTO GDC_SKILL_MASTER VALUES (?)";
        try (final PreparedStatement ps = conn.prepareStatement(insert)) {
            for (final String classTableID : dbSkillMaster.getClassTableList()) {
                ps.setString(1, classTableID);
                ps.executeUpdate();
                ps.clearParameters();
            }
            ps.close();
            conn.commit();
        } catch (SQLException ex) {
            throw ex;
        }
    }

    public static List<String> get() {
        List<String> classTableIDs = null;
        final String command = "SELECT * FROM GDC_SKILL_MASTER";
        try (final Connection conn = GDDBData.getConnection();
             final PreparedStatement ps = conn.prepareStatement(command)) {
            try (final ResultSet rs = ps.executeQuery()) {
                classTableIDs = wrap(rs);
                conn.commit();
            } catch (SQLException ex) {
                throw ex;
            }
        } catch (SQLException ex2) {
            final Object[] args = {"-", "GDC_SKILL_MASTER"};
            final String msg = GDMsgFormatter.format(GDMsgFormatter.rbMsg, "ERR_READ_TABLE_BY_ID", args);
            GDMsgLogger.addError(msg);
            GDMsgLogger.addError(ex2);
        }
        return classTableIDs;
    }

    private static List<String> wrap(final ResultSet rs) throws SQLException {
        final LinkedList<String> list = new LinkedList<String>();
        while (rs.next()) {
            final String classTableID = rs.getString(1);
            list.add(classTableID);
        }
        return list;
    }
}
